import pandas as pd
import sys
from difflib import unified_diff


def read_excel(file_path):
    """读取Excel文件，返回DataFrame"""
    try:
        df = pd.read_excel(file_path, engine="openpyxl")
        print(f"diff中的内容为{df}")
        return df
    except Exception as e:
        print(f"读取文件 {file_path} 时出错: {e}")
        sys.exit(1)


def find_differences(df1, df2):
    """查找两个DataFrame之间的差异"""
    # 将DataFrame转换为字符串格式以便比较
    df1_str = df1.astype(str).apply(lambda x: ' '.join(x), axis=1)
    df2_str = df2.astype(str).apply(lambda x: ' '.join(x), axis=1)
    print(f"diff1 string的内容为\n{df1_str}")
    print(f"diff1 string的内容为\n{df2_str}")
    diff_lines = []

    # 找到新增和删除的行
    set_df1 = set(df1_str)
    print(f"setdiff1的内容为{set_df1}")
    set_df2 = set(df2_str)
    print(f"setdiff2的内容为{set_df2}")
    # 找到新增行
    added = set_df2 - set_df1
    if added:
        diff_lines.append("新增的行:")
        for line in added:
            diff_lines.append(f"  + {line}")

    # 找到删除的行
    removed = set_df1 - set_df2
    if removed:
        diff_lines.append("删除的行:")
        for line in removed:
            diff_lines.append(f"  - {line}")

    # 找到修改的行
    for line in df1_str:
        if line in df2_str:
            continue  # 不需要比较相同的行

        # 查找与其它行的不同之处
        for other_line in df2_str:
            if line != other_line:
                # 使用unified_diff显示变化
                diff = list(unified_diff([line], [other_line], lineterm='', fromfile='old', tofile='new'))
                print(f"unified_diff的值为{diff}")
                if len(diff) > 2:  # 只有在至少有2行差异时才显示
                    diff_lines.append("修改的行:")
                    diff_lines.extend(diff)

    return diff_lines


def main(file1, file2):
    df1 = read_excel(file1)
    df2 = read_excel(file2)

    differences = find_differences(df1, df2)

    if not differences:
        print("两个文件内容一致，未发现差异。")
    else:
        print("\n".join(differences))


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("用法: python excel_diff.py <file1.xlsx> <file2.xlsx>")
        sys.exit(1)

    main(sys.argv[1], sys.argv[2])
